<template>
  <a-modal
    :title="model&&model.id>0?'编辑角色':'新建角色'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    cancelText="取消"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled/>
        </a-form-item>
        <a-form-item label="角色名称">
          <a-input v-decorator="['name', {rules: [{required: true, message: '请输入角色名称'}]}]"/>
        </a-form-item>
        <a-form-item label="角色描述">
          <a-input v-decorator="['describe', {rules: [{required: true, message: '请输入角色描述'}]}]"/>
        </a-form-item>
        <a-form-item label="菜单权限">
          <a-tree
            v-model="resourceIds"
            expandAction="click"
            :checkable="true"
            :selectable="true"
            :replaceFields="{key: 'id'}"
            :expandedKeys="expandedKeys"
            @check="onCheck"
            @select="onSelect"
            :treeData="treeData"
            v-decorator="['resourceIdList']"
          >
            <a-icon slot="switcherIcon" type="caret-down"/>
          </a-tree>
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-decorator="['status',{initialValue: 0}]">
            <a-select-option :value="0">正常</a-select-option>
            <a-select-option :value="1">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { formLayout } from '@/constants/FormConstant'

// 表单字段
const fields = ['name', 'status', 'id']

export default {
  name: 'RoleCreateForm',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    data: {
      type: Function,
      required: true
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      formLayout,
      resourceIds: [],
      expandedKeys: [],
      treeData: [],
      form: this.$form.createForm(this)
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
    this.loadResource()
  },
  methods: {
    // 加载菜单资源
    loadResource() {
      this.data().then(response => {
        this.treeData = response
      })
    },
    // 获取选中的节点id
    onCheck(keys, event) {
      this.$nextTick(() => {
        this.form.setFieldsValue({ resourceIdList: [...event.halfCheckedKeys, ...keys] })
      })
    },
    // 点击节点展开事件
    onSelect(keys) {
      this.expandedKeys = keys
    }
  }
}
</script>
